package org.zjzwx.util;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

import java.io.InputStream;

public class qiniuUtil {

    //密钥
    String token = "";

    //创建上传对象
    UploadManager uploadManager = null;

    public qiniuUtil(String secretKey, String accessKey, String bucketName) {
        //密钥配置
        Auth auth = Auth.create(secretKey, accessKey);
        Zone z = Zone.autoZone();
        Configuration c = new Configuration(z);
        uploadManager = new UploadManager(c);
        token = auth.uploadToken(bucketName);
    }


    public String upload(InputStream stream, String savePath, String mime) {
        String result = "";
        try {
            //调用put方法上传
            Response res = uploadManager.put(stream, savePath, token, new StringMap(), mime);
            //打印返回的信息
            result = res.bodyString();
        } catch (QiniuException e) {
            e.printStackTrace();
            Response r = e.response;
            // 请求失败时打印的异常的信息
            result = r.bodyString();
        } finally {
            return result;
        }
    }
}
